<template>
  <div class="statistics-container">
    <!-- 页面标题与操作按钮 -->
    <div class="page-header">
      <h2 class="page-title">平台数据统计</h2>
      <div class="header-actions">
        <el-button
            type="primary"
            size="small"
            @click="fetchStatistics"
            :loading="refreshing"
            class="refresh-btn"
        >
          <el-icon><Refresh /></el-icon>
          <span>刷新数据</span>
        </el-button>
        <el-button
            type="success"
            size="small"
            @click="exportToExcel"
            :disabled="!hasData"
            class="export-btn"
        >
          <el-icon><Download /></el-icon>
          <span>导出Excel</span>
        </el-button>
      </div>
    </div>

    <!-- 加载状态 -->
    <el-skeleton
        v-if="loading"
        :rows="8"
        :cols="1"
        animated
        class="loading-skeleton"
    ></el-skeleton>

    <!-- 错误提示 -->
    <el-empty
        v-if="error && !loading"
        description="获取数据失败，请点击刷新重试"
        class="error-empty"
    >
      <template #bottom>
        <el-button
            type="primary"
            @click="fetchStatistics"
        >
          刷新数据
        </el-button>
      </template>
    </el-empty>

    <!-- 数据内容 -->
    <template v-if="!loading && !error && Object.keys(statsData).length > 0">
      <!-- 数据概览卡片 -->
      <div class="stats-card-group">
        <!-- 用户统计 -->
        <el-card class="stats-card">
          <div class="stats-header">
            <span class="stats-title">用户统计</span>
            <el-icon class="stats-icon"><User /></el-icon>
          </div>
          <div class="stats-main">
            <div class="stats-number">{{ statsData.totalUser || 0 }}</div>
            <div class="stats-detail">
              <div>活跃: <span class="text-success">{{ statsData.activeUser || 0 }}</span></div>
              <div>禁用: <span class="text-danger">{{ statsData.forbidUser || 0 }}</span></div>
            </div>
          </div>
        </el-card>

        <!-- 商家统计 -->
        <el-card class="stats-card">
          <div class="stats-header">
            <span class="stats-title">商家统计</span>
            <el-icon class="stats-icon"><Shop /></el-icon>
          </div>
          <div class="stats-main">
            <div class="stats-number">{{ statsData.totalMerchant || 0 }}</div>
            <div class="stats-detail">
              <div>活跃: <span class="text-success">{{ statsData.activeMerchant || 0 }}</span></div>
              <div>禁用: <span class="text-danger">{{ statsData.forbidMerchant || 0 }}</span></div>
            </div>
          </div>
        </el-card>

        <!-- 订单统计 -->
        <el-card class="stats-card">
          <div class="stats-header">
            <span class="stats-title">订单统计</span>
            <el-icon class="stats-icon"><Ticket /></el-icon>
          </div>
          <div class="stats-main">
            <div class="stats-number">{{ statsData.totalOrder || 0 }}</div>
            <div class="stats-detail">
              <div>已完成: <span class="text-success">{{ statsData.activeOrder || 0 }}</span></div>
              <div>未完成: <span class="text-danger">{{ statsData.forbidOrder || 0 }}</span></div>
            </div>
          </div>
        </el-card>

        <!-- 支付统计 -->
        <el-card class="stats-card">
          <div class="stats-header">
            <span class="stats-title">支付统计</span>
            <el-icon class="stats-icon"><Money /></el-icon>
          </div>
          <div class="stats-main">
            <div class="stats-number">¥{{ statsData.totalPayment || 0 }}</div>
            <div class="stats-detail">
              <div>有效: <span class="text-success">¥{{ statsData.activePayment || 0 }}</span></div>
              <div>禁用: <span class="text-danger">¥{{ statsData.forbidPayment || 0 }}</span></div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 数据表格 -->
      <el-card class="data-table">
        <div slot="header" class="table-header">
          <span>详细数据统计</span>
          <el-tooltip content="展示平台所有统计指标的详细数据">
            <el-icon class="info-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
        </div>
        <el-table
            :data="tableData"
            border
            stripe
            style="width: 100%"
        >
          <el-table-column
              prop="name"
              label="统计项"
              width="200"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="value"
              label="数值"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="description"
              label="说明"
              align="center"
          ></el-table-column>
        </el-table>
      </el-card>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElSkeleton, ElEmpty, ElTooltip } from 'element-plus'
import {
  User, Shop, Ticket, Money,
  Refresh, QuestionFilled, Download  // 新增下载图标
} from '@element-plus/icons-vue'
import axios from 'axios'
import * as XLSX from 'xlsx'  // 引入xlsx库

// 统计数据
const statsData = ref({})
const loading = ref(true)
const refreshing = ref(false)
const error = ref(false)

// 页面加载时获取统计数据
onMounted(() => {
  fetchStatistics()
})

// 获取统计数据
const fetchStatistics = async () => {
  refreshing.value = true
  error.value = false
  try {
    const response = await axios.get('/api/admin/statistics.do')
    if (response.data.code === 200 && response.data.success) {
      statsData.value = response.data.data || {}
    } else {
      ElMessage.error(response.data.message || '获取统计数据失败')
      error.value = true
    }
  } catch (err) {
    console.error('获取统计数据错误:', err)
    ElMessage.error('网络错误，获取统计数据失败')
    error.value = true
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 表格数据
const tableData = computed(() => [
  { name: '总用户数', value: statsData.value.totalUser || 0, description: '平台注册用户总数' },
  { name: '活跃用户数', value: statsData.value.activeUser || 0, description: '正常使用的用户数量' },
  { name: '禁用用户数', value: statsData.value.forbidUser || 0, description: '被限制使用的用户数量' },
  { name: '总商家数', value: statsData.value.totalMerchant || 0, description: '平台入驻商家总数' },
  { name: '活跃商家数', value: statsData.value.activeMerchant || 0, description: '正常营业的商家数量' },
  { name: '禁用商家数', value: statsData.value.forbidMerchant || 0, description: '被限制营业的商家数量' },
  { name: '总订单数', value: statsData.value.totalOrder || 0, description: '平台创建的订单总数' },
  { name: '已完成订单数', value: statsData.value.activeOrder || 0, description: '有效状态的订单数量' },
  { name: '未完成订单数', value: statsData.value.forbidOrder || 0, description: '被取消或禁用的订单数量' },
  { name: '总支付金额', value: `¥${statsData.value.totalPayment || 0}`, description: '平台交易总金额' },
  { name: '有效支付金额', value: `¥${statsData.value.activePayment || 0}`, description: '正常交易的支付金额' },
  { name: '禁用支付金额', value: `¥${statsData.value.forbidPayment || 0}`, description: '退款或取消的支付金额' }
])

// 判断是否有数据
const hasData = computed(() => Object.keys(statsData.value).length > 0)

// 导出Excel功能
const exportToExcel = () => {
  try {
    // 准备导出数据（包含标题行）
    const exportData = [
      ['统计项', '数值', '说明'],
      ...tableData.value.map(item => [item.name, item.value, item.description])
    ]

    // 创建工作簿和工作表
    const ws = XLSX.utils.aoa_to_sheet(exportData)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '平台统计数据')

    // 生成文件名（包含当前日期）
    const date = new Date()
    const fileName = `优驾租管平台统计数据_${date.getFullYear()}${(date.getMonth() + 1).toString().padStart(2, '0')}${date.getDate().toString().padStart(2, '0')}.xlsx`

    // 导出文件
    XLSX.writeFile(wb, fileName)
    ElMessage.success('Excel导出成功')
  } catch (err) {
    console.error('Excel导出失败:', err)
    ElMessage.error('导出失败，请重试')
  }
}
</script>

<style scoped>
.statistics-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.refresh-btn, .export-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.loading-skeleton {
  margin-bottom: 20px;
}

.error-empty {
  margin: 40px 0;
}

.stats-card-group {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stats-card {
  transition: all 0.3s;
}

.stats-card:hover {
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.08);
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #f0f0f0;
}

.stats-title {
  font-size: 16px;
  font-weight: 500;
  color: #666;
}

.stats-icon {
  font-size: 24px;
  color: #409eff;
}

.stats-number {
  font-size: 26px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.stats-detail {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.text-success {
  color: #67c23a;
  font-weight: 500;
}

.text-danger {
  color: #f56c6c;
  font-weight: 500;
}

.data-table {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.info-icon {
  color: #409eff;
  cursor: pointer;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .stats-card-group {
    grid-template-columns: 1fr;
  }

  .header-actions {
    flex-direction: column;
  }
}
</style>